package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"one-wiki/config"
	"one-wiki/database"
	"one-wiki/middleware"
	"one-wiki/router"
)

func init() {
	// 初始化各项配置
	config.Init()

	// 初始化数据库连接
	database.Init()
}

func main() {

	// 初始化默认的Gin实例,它包含了一组常用的中间件和默认配置
	engine := gin.Default()

	// 注册自定义的权限认证鉴权中间件 为全局中间件
	engine.Use(func(context *gin.Context) {
		method := context.Request.Method
		if method == "OPTIONS" {
			context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			context.Writer.Header().Set("Access-Control-Allow-Methods", "POST,GET")
			context.Writer.Header().Set("Access-Control-Allow-Headers", "*")
			context.AbortWithStatus(http.StatusOK)
			return
		}
		//
		context.Next()
	})

	engine.Use(middleware.ExceptionMiddleware())
	engine.Use(middleware.AuthenticationMiddleware())
	// 初始化路由
	router.InitRouter(engine)

	// 启动
	if err := engine.Run(); err != nil {
		log.Fatalf(err.Error())
	}
}
